#!/usr/bin/env python3
# -*- coding: utf-8 -*-

class MyObject(object):
    #constructor method
    def __init__(self):
        self.x = 9
    #general function
    def power(self):
        return self.x * self.x

obj = MyObject()

print('hasattr(obj, \'x\') =', hasattr(obj, 'x')) # 有属性'x'吗？
print('hasattr(obj, \'y\') =', hasattr(obj, 'y')) # 有属性'y'吗？
setattr(obj, 'y', 19) # 设置一个属性'y'
print('hasattr(obj, \'y\') =', hasattr(obj, 'y')) # 有属性'y'吗？
print('getattr(obj, \'y\') =', getattr(obj, 'y')) # 获取属性'y'
print('obj.y =', obj.y) # 获取属性'y'

print('getattr(obj, \'z\') =',getattr(obj, 'z', 404)) # 获取属性'z'，如果不存在，返回默认值404
#get the attr of obj
f = getattr(obj, 'power') # 获取属性'power'
#the method object
print(f)
#execute the method object
print(f())

#set value to one attr of object, create one new attr if the attr is not found in object
setattr(obj,'age',20)
print(getattr(obj,'age'))
setattr(obj,'age',21)
print(getattr(obj,'age'))
print(getattr(obj,'xage',18)) #get one attr of object,it will return 18 when the attr could be found in object
print(hasattr(obj,'xage'))
print(hasattr(obj,'age'))